package xyz.yuelai.blog.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import xyz.yuelai.blog.entity.User;
import xyz.yuelai.blog.util.EncryptUtil;

/**
 * @author xizi
 * 
 *         身份验证,注册,登录
 * 
 *         2018年8月18日上午9:49:00
 * 
 */
@Controller
@RequestMapping("/auth")
public class AuthController {

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(User user, String code, HttpServletRequest req) {
		String sessionCode = req.getSession().getAttribute("rand").toString();
		System.out.println(user);
		System.out.println(code);
		System.out.println(sessionCode);
		if (sessionCode != null && sessionCode.equalsIgnoreCase(code)) {
			UsernamePasswordToken token = new UsernamePasswordToken(
					user.getEmail(), user.getPassword());
			try {
				SecurityUtils.getSubject().login(token);
				return "redirect:/back/index.html";
			} catch (AuthenticationException e) {
				e.printStackTrace();
				req.setAttribute("msg", "邮箱名或密码错误");
			}
		} else {
			req.setAttribute("msg", "验证码不正确");
		}
		return "/login";
	}

}
